package edu.mama.college.scheduleTask;

import edu.mama.college.model.UserStudyRecord;
import edu.mama.college.service.UserCourseService;
import edu.mama.college.service.UserStudyRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.lang.reflect.Array;
import java.security.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Configuration
@EnableScheduling
public class ScheduleTask {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserCourseService userCourseService;

    @Autowired
    private UserStudyRecordService userStudyRecordService;

    /**
     * 每天凌晨一点更新学生课时状态
     */
    @Scheduled(cron = "0 0 1 * * ?")
    private void setUserCourseStatus(){

        userCourseService.updateStatus();
    }

    /**
     *   每天凌晨一点更新UserStudyRecord表
     */
    @Scheduled(cron ="0 0 1 * * ?")
    private void updateUserStudyRecord(){
        // 昨天的日期
//        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
//        Calendar calendar=Calendar.getInstance();
//        calendar.set(Calendar.HOUR_OF_DAY,-24);
//        String yesterday=dateFormat.format(calendar.getTime());
        String yesterday = LocalDate.now().plusDays(-1).format(DateTimeFormatter.ISO_LOCAL_DATE);

        // 获取keys
        Set<Object> keySet  =  redisTemplate.opsForHash().keys("userStudyRecord::"+yesterday);

        List<UserStudyRecord> UserStudyRecordList = new ArrayList<>();
        // 循环key获取value
        keySet.stream().forEach(key -> {
            if(key!=null){
                // 约定key的格式为`userID,courseId,lessonId`
                String[] id = String.valueOf(key).split(",");
                UserStudyRecord userStudyRecord = new UserStudyRecord();
                userStudyRecord.setUserId( Integer.parseInt(id[0]));
                userStudyRecord.setCourseId( Integer.parseInt(id[1]));
                userStudyRecord.setLessonId( Integer.parseInt(id[2]));
                userStudyRecord.setDate( new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000));
                Object minsObject  = redisTemplate.opsForHash().get("userStudyRecord::"+yesterday,key);
                userStudyRecord.setMins(Integer.parseInt(String.valueOf(minsObject)));

                UserStudyRecordList.add(userStudyRecord);
                redisTemplate.opsForHash().delete("userStudyRecord::"+yesterday,key);

            }

        });

        if(UserStudyRecordList.size() >0){
            userStudyRecordService.scheduleAdd(UserStudyRecordList);
        }
    }
}
